import 'package:flutter/cupertino.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:get/get.dart';

class SetPwdController extends BaseController {
  TextEditingController pwd = TextEditingController();
  TextEditingController pwdConfirm = TextEditingController();
  TextEditingController pay = TextEditingController();
  TextEditingController invite = TextEditingController();

  final pwdFocusNode = FocusNode();
  final pwdConfirmFocusNode = FocusNode();
  final payFocusNode = FocusNode();
  final inviteFocusNode = FocusNode();

  bool isAllCorrect = false;

  String code = Get.arguments['code'];
  String mobile = Get.arguments['mobile'];
  HttpClient client = Get.find<HttpClient>();

  Future<bool> register() async {
    if (!isAllCorrect) return false;
    try {
      DialogUtil.showLoading();
      await client.post(AddressManager.register, data: {
        "code": code,
        "mobile": mobile,
        "password": pwd.text,
        "payPassword": pay.text,
        "shareCode": invite.text,

        /// 1、app，2、H5，默认app
        "type": 1,
      });
      ToastUtil.showSuccess("注册成功!");
      Get.back();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  void onChange() {
    final pattern = RegExp(
        r"^(?=.*[a-zA-Z])(?=.*[0-9!@#\$%\^&\*])(?=.{6,20})(?![\u4e00-\u9fa5]).*$");
    if (!pattern.hasMatch(pwd.text)) {
      return;
    }
    if (pwd.text != pwdConfirm.text) {
      return;
    }
    if (invite.text.isEmpty) {
      return;
    }
    if (pay.text.length != 6) {
      return;
    }
    isAllCorrect = true;
    update();
  }

  void onConfirm() {
    final pattern = RegExp(
        r"^(?=.*[a-zA-Z])(?=.*[0-9!@#\$%\^&\*])(?=.{6,20})(?![\u4e00-\u9fa5]).*$");
    if (!pattern.hasMatch(pwd.text)) {
      ToastUtil.showTips("密码请输入6-20位字符，不可以是纯数字或者符号");
      return;
    }
    if (pwd.text != pwdConfirm.text) {
      ToastUtil.showTips("两次密码不一致");
      return;
    }
    if (invite.text.isEmpty) {
      ToastUtil.showTips("请输入邀请码");
      return;
    }
    if (pay.text.length != 6) {
      ToastUtil.showTips("请输入6位支付密码");
      return;
    }
    register();
  }
}
